package com.suncky.example.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.suncky.example.R
import com.suncky.example.activity.vm.UploadViewModel
import com.suncky.example.adapter.ImageUploadAdapter
import com.suncky.example.databinding.ActivityImageUploadBinding
import com.suncky.example.http.DataPage
import com.suncky.example.http.ParamsInterceptor
import com.suncky.example.http.UploadHttpCallback1
import com.suncky.example.http.UploadHttpResult
import com.suncky.example.http.UploadHttpResult1
import com.suncky.frame.AppConfig
import com.suncky.frame.base.adapter.ImageEditGridAdapter
import com.suncky.frame.base.mvvm.BaseMvvmActivity
import com.suncky.frame.dialog.ImagePickerDialog
import com.suncky.frame.dialog.ImageViewerDialog
import com.suncky.frame.http.file.UploadCallback
import com.suncky.frame.http.file.Uploader
import com.suncky.frame.utils.ImagePickHelper
import com.suncky.frame.utils.LogUtils
import com.suncky.frame.utils.glide.GlideUtils
import com.suncky.frame.widget.recyclerview.GridDividerItemDecoration
import java.io.File

class ImageUploadActivity : BaseMvvmActivity<ActivityImageUploadBinding, UploadViewModel>() {

    companion object{
        const val MAX_IMAGE_COUNT = 6
        fun start(context: Context){
            val starter = Intent(context, ImageUploadActivity::class.java)
            if (context !is Activity) {
                starter.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(starter)
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_image_upload
    }

    private val urlList = mutableListOf<String>()
    private lateinit var imageAdapter:ImageEditGridAdapter
    private val imagePickerHelper by lazy {
        ImagePickHelper.with(this)
                .crop(false)
                .destinationPath(AppConfig.imagePath)
                .callBack { uri, path ->
                    imageAdapter.addImage(path)
                    imageViewerDialog.notifyImageDataChanged()
                }
    }
    private val imagePickerDialog by lazy {
        ImagePickerDialog(
                context
        ) { o, dialog, extras ->
            when (o) {
                ImagePickerDialog.PICKER_TYPE_ALBUM -> imagePickerHelper.album()
                ImagePickerDialog.PICKER_TYPE_CAMERA -> imagePickerHelper.camera()
            }
        }.apply { this.setTitle("选择图片")}
    }
    private val imageViewerDialog by lazy {
        object : ImageViewerDialog<String>(context, urlList) {
            override fun onGetDesc(item: String?, position: Int): String? = null

            override fun onShowImage(item: String?, position: Int, imageView: ImageView?) {
                GlideUtils.load(context,item,imageView,0)
            }
        }
    }

    override fun initView() {
        super.initView()
        defaultTitle.setTitle("文件图片")
        defaultTitle.setRightText("提交")

        binding.rvImage.layoutManager = GridLayoutManager(context, 3)
        binding.rvImage.addItemDecoration(
            GridDividerItemDecoration(
                resources.getDimensionPixelOffset(com.suncky.frame.R.dimen.dp_10),
                resources.getColor(R.color.white),
                GridDividerItemDecoration.VERTICAL
            )
        )
        imageAdapter = object : ImageEditGridAdapter(context, urlList, maxCount = MAX_IMAGE_COUNT) {
            override fun onDelete(position: Int) {
                this.removeImage(position)
                imageViewerDialog.notifyImageDataChanged()
            }

            override fun onGetImageUrl(item: String?, position: Int): String? {
                return item
            }

            override fun onAddImage(position: Int) {
                imagePickerDialog.show()
            }

            override fun onViewImage(item: String?, position: Int) {
                imageViewerDialog.open(position)
            }

        }

        binding.rvImage.adapter = imageAdapter
    }

    override fun initData() {
        super.initData()
    }

    override fun onDefaultRightTextClick() {
        upload()
    }

    private fun upload() {
        val files = urlList.flatMap { listOf(File(it)) }.toTypedArray()
        val uploader = Uploader.Builder(context)
            .url("http://192.168.1.102:8809/office/upload/photo")
            .formName("file")
            .addInterceptor(ParamsInterceptor()).build()
        uploader.upload(files, object : UploadHttpCallback1() {

            override fun onStart() {
                showLoadingPop("正在上传图片")
            }

            override fun onProgress(progress: Long, total: Long) {
                LogUtils.i("progress--->$progress  total--->$total")
//                                if (progress * 100 / total > 50) {
//                                    uploader.cancel(File(path))
//                                }
            }

            override fun onSuccess(result: UploadHttpResult1) {
                dismissLoadingPop()
                com.suncky.frame.utils.ToastUtils.toast("上传成功")
                LogUtils.i(result.data)
            }

            override fun onFailure(message: String?) {
                dismissLoadingPop()
                com.suncky.frame.utils.ToastUtils.toast("上传失败：$message")
                LogUtils.i(message)
            }

            override fun onCancel(requestTag: Any?) {
                super.onCancel(requestTag)
                dismissLoadingPop()
                com.suncky.frame.utils.ToastUtils.toast("上传已取消:tag=$requestTag")
            }
        })
    }

    val callback= object : UploadCallback<List<String>, DataPage, UploadHttpResult>() {


        override fun onProgress(progress: Long, total: Long) {
            LogUtils.i("progress--->$progress  total--->$total")
//                            if (progress * 100 / total > 50) {
//                                uploader.cancel("upload task 2")
//                            }
        }

        override fun onSuccess(result: UploadHttpResult) {
            LogUtils.printList(result.data)
            com.suncky.frame.utils.ToastUtils.toast("上传成功")
        }

        override fun onFailure(message: String?) {
            com.suncky.frame.utils.ToastUtils.toast("上传失败：$message")
        }

        override fun onCancel(requestTag: Any?) {
            super.onCancel(requestTag)
            com.suncky.frame.utils.ToastUtils.toast("上传已取消:tag=$requestTag")
        }
    }
    open class MyCallBack: UploadCallback<List<String>, DataPage, UploadHttpResult>(){
        override fun onProgress(progress: Long, total: Long) {
            LogUtils.i("progress--->$progress  total--->$total")
//                            if (progress * 100 / total > 50) {
//                                uploader.cancel("upload task 2")
//                            }
        }

        override fun onSuccess(result: UploadHttpResult) {
            LogUtils.printList(result.data)
            com.suncky.frame.utils.ToastUtils.toast("上传成功")
        }

        override fun onFailure(message: String?) {
            com.suncky.frame.utils.ToastUtils.toast("上传失败：$message")
        }

        override fun onCancel(requestTag: Any?) {
            super.onCancel(requestTag)
            com.suncky.frame.utils.ToastUtils.toast("上传已取消:tag=$requestTag")
        }
    }

    open class MyCallBack1 : MyCallBack() {

    }
    open class MyCallBack2 : MyCallBack1() {

    }
    class MyCallBack3 : MyCallBack2() {

    }
}
